package com.cssw.fyzb.tps.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;

/**
 * @author Feng Chen
 */
public class VodSignature {

    private static final Random RANDOM = new Random();
    private static final BASE64Encoder ENCODER = new BASE64Encoder();

    private static final String HMAC_ALGORITHM = "HmacSHA1";
    private static final String CONTENT_CHARSET = "UTF-8";

    private static final Logger logger = LoggerFactory.getLogger(VodSignature.class);


    // 获取签名
    public static String getSig(String secretId, String secretKey, long currentTimestamp, long expireTimestamp) throws Exception {
        String strSign = "";
        String contextStr = "";
        // 生成原始参数字符串
        contextStr += "secretId=" + java.net.URLEncoder.encode(secretId, "utf8");
        contextStr += "&currentTimeStamp=" + currentTimestamp;
        contextStr += "&expireTime=" + expireTimestamp;
        contextStr += "&random=" + RANDOM.nextInt(Integer.MAX_VALUE);
        Mac mac = Mac.getInstance(HMAC_ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(CONTENT_CHARSET), mac.getAlgorithm());
        mac.init(secretKeySpec);
        byte[] hash = mac.doFinal(contextStr.getBytes(CONTENT_CHARSET));
        byte[] sigBuf = byteMerger(hash, contextStr.getBytes("utf8"));
        strSign = ENCODER.encode(sigBuf);
        strSign = strSign.replace(" ", "").replace("\n", "").replace("\r", "");
        return strSign;
    }

    private static byte[] byteMerger(byte[] byte1, byte[] byte2) {
        byte[] byte3 = new byte[byte1.length + byte2.length];
        System.arraycopy(byte1, 0, byte3, 0, byte1.length);
        System.arraycopy(byte2, 0, byte3, byte1.length, byte2.length);
        return byte3;
    }

    public static void main(String[] args) throws Exception {
        long now = System.currentTimeMillis() / 1000;
        System.out.println(VodSignature.getSig("AKIDgAPN4km0XnNlshradPtVs64b9UYKs4fx", "DCvOf6JJ4vay6xaw0sgwve6E5fyNWP08", now, now + 3600 * 24 * 2));
    }


}
